package com.hongdee.insurance.schedule;

import com.hongdee.annotation.MethodComment;
import com.hongdee.crm.task.dao.ITCrmTaskLogDao;
import com.hongdee.crm.task.entity.TCrmTaskLog;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
 * Created by My on 2017/4/6.
 */
@Aspect
@Configuration
public class InsuranceTaskQuartzAop {

    @Autowired
    private ITCrmTaskLogDao crmTaskLogDao;

    @Pointcut("execution(* com.hongdee.insurance.task.service.*.*Quartz(..))")
    public void excudeService(){}

    @Around("excudeService()")
    public Object twiceAsOld(ProceedingJoinPoint thisJoinPoint) throws Exception {
        TCrmTaskLog crmTaskLog=new TCrmTaskLog();
        // 定义返回对象、得到方法需要的参数
        Object obj = null;
        Object[] args = thisJoinPoint.getArgs();
        long startTime = System.currentTimeMillis();
        try {
            obj = thisJoinPoint.proceed(args);
            if(obj!=null) {
                crmTaskLog.setResult(obj.toString());
            }
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            crmTaskLog.setExMessage(throwable.getMessage());
        }
        // 获取执行的方法名
        long endTime = System.currentTimeMillis();
        crmTaskLog.setStartTime(startTime);
        crmTaskLog.setEndTime(endTime);

        MethodSignature signature = (MethodSignature) thisJoinPoint.getSignature();
        String methodName = signature.getDeclaringTypeName() + "." + signature.getName();
        crmTaskLog.setMethodName(methodName);
        Method method=signature.getMethod();

        Method methodImpl=thisJoinPoint.getTarget().getClass().getDeclaredMethod(signature.getName(), method.getParameterTypes());
        Annotation annotation=methodImpl.getAnnotation(MethodComment.class);
        MethodComment methodComment=(MethodComment)annotation;
        crmTaskLog.setMethodComment(methodComment.name());
        crmTaskLog.setMethodName(method.getName());
        crmTaskLog.setClassPath(method.getDeclaringClass().getName());
        crmTaskLogDao.saveOrUpdate(crmTaskLog);
        return null;
    }
}
